package com.event.management.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.event.management.backend.domain.LoginLogs;
import com.event.management.backend.service.LoginLogsService;
import com.event.management.backend.mapper.LoginLogsMapper;
import com.event.management.backend.dto.LoginLogQueryDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
* @author HY
* @description 针对表【login_logs(登录日志表)】的数据库操作Service实现
* @createDate 2025-04-04 17:38:12
*/
@Slf4j
@Service
public class LoginLogsServiceImpl extends ServiceImpl<LoginLogsMapper, LoginLogs>
    implements LoginLogsService{

    /**
     * 分页查询登录日志
     * @param queryDTO 查询参数
     * @return 分页结果
     */
    @Override
    public Page<LoginLogs> getLoginLogPage(LoginLogQueryDTO queryDTO) {
        log.info("分页查询登录日志: pageNum={}, pageSize={}, userId={}", 
                queryDTO.getPageNum(), queryDTO.getPageSize(), queryDTO.getUserId());
        
        // 构建查询条件
        LambdaQueryWrapper<LoginLogs> queryWrapper = new LambdaQueryWrapper<>();
        
        // 按用户ID查询
        if (queryDTO.getUserId() != null) {
            queryWrapper.eq(LoginLogs::getUserId, queryDTO.getUserId());
        }
        
        // 按时间范围查询
        if (queryDTO.getStartTime() != null) {
            queryWrapper.ge(LoginLogs::getLoginTime, queryDTO.getStartTime());
        }
        
        if (queryDTO.getEndTime() != null) {
            queryWrapper.le(LoginLogs::getLoginTime, queryDTO.getEndTime());
        }
        
        // 按时间倒序排序
        queryWrapper.orderByDesc(LoginLogs::getLoginTime);
        
        // 执行分页查询
        Page<LoginLogs> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        Page<LoginLogs> resultPage = page(page, queryWrapper);
        
        log.info("查询结果: 总记录数={}, 总页数={}", resultPage.getTotal(), resultPage.getPages());
        return resultPage;
    }
    
    /**
     * 记录登录日志
     * @param userId 用户ID
     * @param ipAddress IP地址
     * @param status 登录状态（成功/失败）
     * @return 是否记录成功
     */
    @Override
    public boolean addLoginLog(Integer userId, String ipAddress, String status) {
        log.info("记录登录日志: userId={}, ipAddress={}, status={}", userId, ipAddress, status);
        
        try {
            LoginLogs loginLog = new LoginLogs();
            loginLog.setUserId(userId);
            loginLog.setIpAddress(ipAddress);
            loginLog.setStatus(status);
            loginLog.setLoginTime(new Date());
            
            boolean saved = save(loginLog);
            log.info("登录日志记录{}", saved ? "成功" : "失败");
            return saved;
        } catch (Exception e) {
            log.error("记录登录日志失败: userId={}, error={}", userId, e.getMessage());
            return false;
        }
    }
    
    /**
     * 获取用户最后一次成功登录记录
     * @param userId 用户ID
     * @return 登录记录
     */
    @Override
    public LoginLogs getLastSuccessfulLogin(Integer userId) {
        log.info("获取用户最后一次成功登录记录: userId={}", userId);
        
        try {
            // 构建查询条件
            LambdaQueryWrapper<LoginLogs> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LoginLogs::getUserId, userId)
                    .eq(LoginLogs::getStatus, "success")  // 只查询成功登录记录
                    .orderByDesc(LoginLogs::getLoginTime)  // 按时间倒序
                    .last("LIMIT 1");  // 只取最后一条
            
            LoginLogs lastLogin = getOne(queryWrapper);
            log.info("查询结果: {}", lastLogin);
            return lastLogin;
        } catch (Exception e) {
            log.error("获取用户最后一次成功登录记录失败: userId={}, error={}", userId, e.getMessage());
            return null;
        }
    }
}




